package org.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.demo.entity.ThoughtReport;
import org.example.demo.entity.User;
import org.example.demo.service.ThoughtReportService;
import org.example.demo.service.UserService;
import org.example.demo.util.AjaxResult;
import org.example.demo.util.ReturnMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("thought/report")
public class ThoughtReportController {

    @Resource
    private ThoughtReportService thoughtReportService;

    @Resource
    private UserService userService;

    // 分页查询思想汇报列表
    @PostMapping("selectPage")
    public AjaxResult selectPage(@RequestBody ThoughtReport report,
                                 @RequestParam(defaultValue = "1") Integer pageNum,
                                 @RequestParam(defaultValue = "10") Integer pageSize) {
//        ReturnMap returnMap = new ReturnMap();
        Map<String, Object> map = new HashMap<>();
        Page<ThoughtReport> page = new Page<>(pageNum, pageSize);
        // 收集所有用户
        Map<Long, User> userMap = userService.list(new QueryWrapper<User>().lambda().like(report.getNickName() != null && !report.getNickName().isEmpty(), User::getName, report.getNickName())).stream()
                .collect(Collectors.toMap(User::getId, user -> user));
        if (!userMap.isEmpty()) {
            QueryWrapper<ThoughtReport> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .in(ThoughtReport::getUserId, userMap.keySet())
                    .eq(report.getUserId() != null && report.getUserId() != 0L, ThoughtReport::getUserId, report.getUserId())
                    .like(null != report.getTitle() && !report.getTitle().isEmpty(),
                            ThoughtReport::getTitle, report.getTitle())
                    .orderByDesc(ThoughtReport::getCreateTime);

            Page<ThoughtReport> result = thoughtReportService.page(page, queryWrapper);

            // 遍历结果集，设置用户昵称
            for (ThoughtReport thoughtReport : result.getRecords()) {
                User user = userMap.get(thoughtReport.getUserId());
                if (user != null) {
                    thoughtReport.setNickName(user.getName());
                }
            }
            map.put("page", result);
//            returnMap.setData("page", result);
        } else {
            map.put("page", new ArrayList<>());
//            returnMap.setData("page", new ArrayList<>());
        }

        return AjaxResult.success(map);
    }

    // 查询思想汇报详情
    @GetMapping("detail")
    public AjaxResult detail(@RequestParam Integer id) {
//        ReturnMap returnMap = new ReturnMap();
        Map<String, Object> map = new HashMap<>();
        ThoughtReport report = thoughtReportService.getById(id);

        map.put("report", report);
//        returnMap.setData("report", report);
        return AjaxResult.success(map);
    }

    // 提交思想汇报
    @PostMapping("submit")
    public AjaxResult submit(@RequestBody ThoughtReport report) {
//        ReturnMap returnMap = new ReturnMap();

        if (report.getId() != null) {
            report.setUpdateTime(LocalDateTime.now());
            thoughtReportService.updateById(report);
        } else {
            report.setCreateTime(LocalDateTime.now());
            report.setUpdateTime(LocalDateTime.now());
            thoughtReportService.save(report);
        }

//        returnMap.setReturnCode(200);
        return AjaxResult.success();
    }


    // 获取申请人最新思想汇报
    @GetMapping("latestByApplicant")
    public AjaxResult getLatestByApplicant(@RequestParam Integer applicantId) {
//        ReturnMap returnMap = new ReturnMap();

        QueryWrapper<ThoughtReport> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(ThoughtReport::getUserId, applicantId)
                .orderByDesc(ThoughtReport::getReportDate)
                .last("LIMIT 1");

        ThoughtReport report = thoughtReportService.getOne(queryWrapper);

        Map<String, Object> map = new HashMap<>();
        map.put("report", report);
//        returnMap.setData("report", report);
        return AjaxResult.success(map);
    }

    // 删除思想汇报
    @DeleteMapping("delete")
    public AjaxResult delete(@RequestParam Integer id) {
//        ReturnMap returnMap = new ReturnMap();
        boolean success = thoughtReportService.removeById(id);

        if (success) return AjaxResult.success();
        return AjaxResult.error();
//        returnMap.setReturnCode(success ? 200 : 405);
//        return returnMap.getreturnMap();
    }

    // 查询总数
    @PostMapping("selectCount")
    public AjaxResult selectCount(@RequestBody ThoughtReport report) {
//        ReturnMap returnMap = new ReturnMap();

        Map<String, Object> map = new HashMap<>();
        // 收集所有用户
        Map<Long, User> userMap = userService.list(new QueryWrapper<User>().lambda().like(report.getNickName() != null && !report.getNickName().isEmpty(), User::getName, report.getNickName())).stream()
                .collect(Collectors.toMap(User::getId, user -> user));
        if (!userMap.isEmpty()) {
            QueryWrapper<ThoughtReport> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().in(ThoughtReport::getUserId, userMap.keySet())

                    .eq(report.getUserId() != null && report.getUserId() != 0L, ThoughtReport::getUserId, report.getUserId())
                    .like(null != report.getTitle() && !report.getTitle().isEmpty(), ThoughtReport::getTitle, report.getTitle());

            int count = thoughtReportService.count(queryWrapper);
//            returnMap.setData("count", count);
            map.put("count", count);
        } else {
            map.put("count", 0);
//            returnMap.setData("count", 0);
        }

        return AjaxResult.success(map);
    }
}
